<template>
	<div class="company_box">
		<div class="company_title">组织架构</div>

		<!-- 搜索区域 - 实现实时搜索 -->
		<div class="account_search">
			<div class="search_box">
				<el-input 
					v-model="name_serch" 
					class="name_search input" 
					placeholder="请输入公司名称" 
					:clearable="true"
					@input="handleSearchInput"
				/>
			</div>
		</div>

		<!-- 表格区域 -->
		<el-table 
			:data="currentPageData" 
			style="width: 100%; margin-bottom: 20px" 
			row-key="id" 
			border 
			:tree-props="{ children: 'project', hasChildren: 'hasChildren' }"
			:loading="loading"
			@row-click="handleRowClick"
			highlight-current-row
		>
			<el-table-column prop="id" label="序号" width="100" />
			<el-table-column label="公司名称" min-width="200">
        <template #default="scope">
          {{ getDisplayName(scope.row) }}
        </template>
      </el-table-column>
			<el-table-column label="总人数" width="120">
				<template #default="scope">
					{{ calculateTotal(scope.row) }}
				</template>
			</el-table-column>
			<el-table-column prop="long" label="长期派遣人数" width="120" />
			<el-table-column prop="samll" label="短期派遣人数" width="120" />
			<el-table-column prop="student" label="学员人数" width="120" />
		</el-table>
		
		<!-- 优化后的抽屉 -->
		<el-drawer
			v-model="drawerVisible"
			title="公司详情"
			direction="rtl"
			size="70%"
			:destroy-on-close="true"
			:before-close="handleDrawerClose"
		>
			<!-- 选项卡组件 -->
			<el-tabs v-model="activeTab" class="mt-4" @tab-change="handleTabChange">
				<!-- 详细资料选项卡 -->
				<el-tab-pane label="详细资料" name="details">
					<el-card>
						<el-form :model="selectedRow" label-width="150px" class="detail-form">
							<el-row :gutter="20">
								<el-col :span="12">
									<el-form-item label="公司名称">
										<el-input v-model="selectedRow.account" disabled />
									</el-form-item>
									<el-form-item label="长期派遣人数">
										<el-input v-model="selectedRow.long" disabled />
									</el-form-item>
									<el-form-item label="短期派遣人数">
										<el-input v-model="selectedRow.samll" disabled />
									</el-form-item>
									<el-form-item label="学员人数">
										<el-input v-model="selectedRow.student" disabled />
									</el-form-item>
								</el-col>
								<el-col :span="12">
									<el-form-item label="一档人数">
										<el-input v-model="selectedRow.one" disabled />
									</el-form-item>
									<el-form-item label="二档人数">
										<el-input v-model="selectedRow.two" disabled />
									</el-form-item>
									<el-form-item label="三档人数">
										<el-input v-model="selectedRow.three" disabled />
									</el-form-item>
									<el-form-item label="四档人数">
										<el-input v-model="selectedRow.foure" disabled />
									</el-form-item>
									<el-form-item label="总人数">
										<el-input v-model="totalPeople" disabled />
									</el-form-item>
								</el-col>
							</el-row>
						</el-form>
					</el-card>
				</el-tab-pane>
				
				<!-- 员工列表选项卡 -->
				<el-tab-pane label="员工列表" name="employees">
					<el-card>
						<div class="employee-filters mb-4">
							<el-input 
								v-model="employeeSearch.name" 
								placeholder="搜索员工姓名" 
								class="w-64 mr-4"
								:clearable="true"
								@input="handleEmployeeSearch"
							/>
							<el-select 
								v-model="employeeSearch.type" 
								placeholder="选择用工形式" 
								class="w-48"
								clearable
								@change="handleEmployeeSearch"
							>
								<el-option label="长期派遣" value="long" />
								<el-option label="短期派遣" value="small" />
								<el-option label="学员" value="student" />
							</el-select>
						</div>
						
						<el-table 
							:data="pagedEmployees" 
							border 
							style="width: 100%"
							:loading="employeeLoading"
							empty-text="暂无员工数据"
						>
							<el-table-column prop="name" label="姓名"/>
							<el-table-column prop="tel" label="电话"/>
							<el-table-column prop="gender" label="性别">
								<template #default="scope">
									{{ scope.row.gender === 'male' ? '男' : '女' }}
								</template>
							</el-table-column>
							<el-table-column prop="type" label="用工形式">
								<template #default="scope">
										{{ getTypeName(scope.row.type) }}
								</template>
							</el-table-column>
							<el-table-column prop="createTime" label="创建时间"/>
						</el-table>
						
						<!-- 员工列表分页 -->
						<div class="pagination-container mt-4">
							<el-pagination 
								background 
								layout="total, sizes, prev, pager, next, jumper" 
								:total="filteredEmployees.length"
								:page-size="employeePageSize"
								:page-sizes="[10, 20, 50]"
								:current-page="employeeCurrentPage"
								@size-change="handleEmployeeSizeChange"
								@current-change="handleEmployeeCurrentChange"
								:disabled="employeeLoading"
							/>
						</div>
					</el-card>
				</el-tab-pane>
			</el-tabs>
		</el-drawer>

		<!-- 分页 -->
		<div class="pagination-container">
			<el-pagination 
				background 
				layout="total, sizes, prev, pager, next, jumper" 
				:total="filteredTotal"
				:page-size="pageSize"
				:page-sizes="[10, 20, 50, 100]"
				:current-page="currentPage"
				@size-change="handleSizeChange"
				@current-change="handleCurrentChange"
				:disabled="loading"
			/>
		</div>
	</div>
</template>

<script lang="ts" setup>
import { ref, computed, onMounted, watch, reactive } from 'vue';
import { getOrgTree,getStaffList } from '../../api/account/index.js';
import { ElMessage, ElMessageBox } from 'element-plus';

// 组织数据接口定义
interface OrgData {
	id: number;
	account: string;
	title: string;
	long: number;
	samll: number;
	student: number;
	foure?: number;
	one?: number;
	three?: number;
	two?: number;
	manage: { account: string } | null;
	project?: Array<any>;
	hasChildren?: boolean;
}

// 员工数据接口定义
interface Employee {
	id: number;
	name: string;
	tel: string;
	gender: 'male' | 'female';
	type: 'long' | 'small' | 'student';
	createTime: string;
}
// 防抖函数
const debounce = (fn: Function, delay: number) => {
	let timer: NodeJS.Timeout | null = null;
	return (...args: any[]) => {
		if (timer) clearTimeout(timer);
		timer = setTimeout(() => {
			fn.apply(this, args);
			timer = null;
		}, delay);
	};
};

// 数据和状态管理
const allData = ref<OrgData[]>([]);
const filteredData = ref<OrgData[]>([]);
const name_serch = ref('');
const loading = ref(false);

// 分页相关
const currentPage = ref(1);
const pageSize = ref(10);

// 计算过滤后的总条数
const filteredTotal = computed(() => filteredData.value.length);

// 计算当前页数据
const currentPageData = computed(() => {
	const startIndex = (currentPage.value - 1) * pageSize.value;
	const endIndex = startIndex + pageSize.value;
	return filteredData.value.slice(startIndex, endIndex);
});

// 抽屉相关
const drawerVisible = ref(false);
const selectedRow = ref<OrgData>({} as OrgData);
const activeTab = ref('details');
const totalPeople = computed(() => {
	return selectedRow.value ? calculateTotal(selectedRow.value) : 0;
});

// 员工列表相关
const employees = ref<Employee[]>([]);
const employeeLoading = ref(false);
const employeeSearch = reactive({
	name: '',
	type: ''
});
const employeeCurrentPage = ref(1);
const employeePageSize = ref(10);

// 过滤后的员工列表
const filteredEmployees = computed(() => {
	return employees.value.filter(emp => {
		const nameMatch = emp.name.toLowerCase().includes(employeeSearch.name.toLowerCase());
		const typeMatch = !employeeSearch.type || emp.type === employeeSearch.type;
		return nameMatch && typeMatch;
	});
});

// 分页处理后的员工数据
const pagedEmployees = computed(() => {
	const startIndex = (employeeCurrentPage.value - 1) * employeePageSize.value;
	const endIndex = startIndex + employeePageSize.value;
	return filteredEmployees.value.slice(startIndex, endIndex);
});

// 获取组织架构数据
const fetchOrgData = async () => {
	if (loading.value) return; // 防止重复请求
	
	loading.value = true;
	try {
		const params = {
			name: name_serch.value || undefined
		};
		
		const res = await getOrgTree(params);
		allData.value = res.data || [];
		filterData();
	} catch (error) {
		console.error('获取组织架构数据失败:', error);
		ElMessage.error('获取数据失败，请重试');
	} finally {
		loading.value = false;
	}
};

// 根据搜索关键词过滤数据
const filterData = () => {
	if (!name_serch.value) {
		filteredData.value = [...allData.value];
	} else {
		const searchTerm = name_serch.value.toLowerCase();
		filteredData.value = filterOrgData(allData.value, searchTerm);
	}
	currentPage.value = 1;
};

// 递归过滤组织数据
const filterOrgData = (data: OrgData[], searchTerm: string): OrgData[] => {
	return data.reduce((acc, item) => {
		const isMatch = item.account.toLowerCase().includes(searchTerm);
		const filteredChildren = item.project ? filterOrgData(item.project, searchTerm) : [];
		
		if (isMatch || filteredChildren.length > 0) {
			acc.push({
				...item,
				project: filteredChildren,
				hasChildren: filteredChildren.length > 0
			});
		}
		
		return acc;
	}, [] as OrgData[]);
};

// 计算总人数（仅当前部门，不包含子部门）
const calculateTotal = (row: OrgData): number => {
	return (row.long || 0) + (row.samll || 0) + (row.student || 0);
};

// 获取显示名称（一级用account，子级用title）
const getDisplayName = (row: OrgData): string => {
	return row.account || row.title || '';
};

// 处理搜索输入（防抖处理）
const handleSearchInput = debounce(() => {
	filterData();
}, 300);

// 分页处理函数
const handleSizeChange = (size: number) => {
	pageSize.value = size;
	currentPage.value = 1;
};

const handleCurrentChange = (page: number) => {
	currentPage.value = page;
};

// 行点击事件 - 打开抽屉并加载数据
const handleRowClick = async (row: OrgData) => {
	// 如果点击的是当前已选中的行且抽屉已打开，则不重复加载
	if (drawerVisible.value && selectedRow.value.id === row.id) {
		return;
	}
	
	selectedRow.value = { ...row };
	drawerVisible.value = true;
	activeTab.value = 'details';
	
	// 加载员工数据
	await fetchEmployees(row.id);
};
// 获取员工数据
const fetchEmployees = async (orgId: number) => {
	if (employeeLoading.value) return; // 防止重复请求
	
	employeeLoading.value = true;
	try {
		// 使用新的接口获取员工数据，参数名为companyid
		const res = await getStaffList({ companyid: orgId });
		
		// 映射返回的数据字段到前端使用的字段
		employees.value = (res.data || []).map((item: any) => ({
			id: item.id,
			name: item.name,
			tel: item.tel,
			gender: item.sex === 1 ? 'male' : 'female',
			type: item.layout === 1 ? 'long' : item.layout === 2 ? 'small' : 'student',
			createTime: item.create_time
		}));
		
		employeeCurrentPage.value = 1; // 重置到第一页
	} catch (error) {
		console.error('获取员工数据失败:', error);
		ElMessage.error('获取员工数据失败，请重试');
		employees.value = [];
	} finally {
		employeeLoading.value = false;
	}
};
// 员工搜索处理（防抖）
const handleEmployeeSearch = debounce(() => {
	employeeCurrentPage.value = 1; // 搜索时重置到第一页
}, 300);

// 员工列表分页处理
const handleEmployeeSizeChange = (size: number) => {
	employeePageSize.value = size;
	employeeCurrentPage.value = 1;
};

const handleEmployeeCurrentChange = (page: number) => {
	employeeCurrentPage.value = page;
};

// 选项卡切换处理
const handleTabChange = (tabName: string) => {
	// 切换到员工列表时，如果还没有加载数据则加载
	if (tabName === 'employees' && employees.value.length === 0 && selectedRow.value.id) {
		fetchEmployees(selectedRow.value.id);
	}
};

// 抽屉关闭前处理
const handleDrawerClose = (done: () => void) => {
	// 如果正在加载数据，提示用户
	if (employeeLoading.value) {
		ElMessageBox.confirm('正在加载数据，确定要关闭吗？')
			.then(() => {
				done();
				resetEmployeeData();
			})
			.catch(() => {
				// 不关闭抽屉
			});
	} else {
		done();
		resetEmployeeData();
	}
};

// 重置员工数据
const resetEmployeeData = () => {
	employees.value = [];
	employeeSearch.name = '';
	employeeSearch.type = '';
	employeeCurrentPage.value = 1;
};

// 辅助函数：获取用工形式标签类型
const getTagType = (type: string) => {
	switch(type) {
		case 'long': return 'success';
		case 'small': return 'warning';
		case 'student': return 'info';
		default: return 'default';
	}
};

// 辅助函数：获取用工形式名称
const getTypeName = (type: string) => {
	switch(type) {
		case 'long': return '长期派遣';
		case 'small': return '短期派遣';
		case 'student': return '学员';
		default: return '未知';
	}
};

// 初始化数据
onMounted(() => {
	fetchOrgData();
});
</script>

<style scoped>
.company_box {
	width: 100%;
	background-color: #fff;
	padding: 20px;
	min-height: calc(100vh - 40px);
}

.company_title {
	background: #fff;
	width: 100%;
	height: 60px;
	font-size: 24px;
	font-weight: 500;
	display: flex;
	align-items: center;
	border-bottom: 1px solid #eee;
	margin-bottom: 20px;
	padding-left: 10px;
}

.account_search {
	display: flex;
	justify-content: flex-start;
	margin-bottom: 20px;
}

/* 输入框样式 */
.input {
	width: 300px;
}

/* 分页容器样式 */
.pagination-container {
	display: flex;
	justify-content: center;
	padding: 20px 0;
}

/* 详情表单样式 */
.mt-4{
	margin-left: 20px;
}
.employee-filters>.w-64{
width: 20%;
}
.detail-form {
	margin-top: 20px;
}

.detail-form .el-form-item {
	margin-bottom: 15px;
}

/* 员工过滤器样式 */
.employee-filters {
	display: flex;
	align-items: center;
}

/* 卡片样式 */
:deep(.el-card) {
	margin-bottom: 16px;
}

/* 表格行悬停效果优化 */
:deep(.el-table__row:hover > td) {
	background-color: #f5f7fa !important;
}

/* 当前行高亮样式 */
:deep(.el-table__row.current-row > td) {
	background-color: #e6f7ff !important;
}
</style>
